const request = require('./request')

const BASE_URL = '/wechat/api/miniapp'

// 防重复：openid 与 登录并发控制
let openidRequestInProgress = false;
let openidPromise = null;
let loginRequestInProgress = false;
let loginByOpenidPromise = null;

/**
 * 获取openid
 * @param {*} code 
 */
function getOpenid(code) {
  if (openidRequestInProgress && openidPromise) {
    return openidPromise;
  }
  openidRequestInProgress = true;
  openidPromise = request.post(BASE_URL + '/get/openid', { code: code }).then(data => {
    if (data && data.openid) {
      wx.setStorageSync('openid', data.openid)
      wx.setStorageSync('sessionKey', data.sessionKey)
      wx.setStorageSync('unionid', data.unionid)
      return loginByOpenid(data.openid, data.unionid)
    }
    return data;
  }).finally(() => {
    openidRequestInProgress = false;
    openidPromise = null;
  });
  return openidPromise;
}

/**
 * 通过openid登录
 * @param {*} openid 
 */
function loginByOpenid(openid, unionid) {
  if (loginRequestInProgress && loginByOpenidPromise) {
    return loginByOpenidPromise;
  }
  loginRequestInProgress = true;
  loginByOpenidPromise = request.post(BASE_URL + '/openid/login', { openid, unionid }).then(res => {
    console.log('data=', res)
    if (res){
      wx.setStorageSync('userInfo', res)
    }
    if (res && res.token) {
      wx.setStorageSync('token', res.token)
      const app = (typeof getApp === 'function') ? getApp() : null
      if (app && typeof app.getAccountGlobal === 'function') {
        app.getAccountGlobal()
      }
    }
    return res;
  }).finally(() => {
    loginRequestInProgress = false;
    loginByOpenidPromise = null;
  });
  return loginByOpenidPromise;
}

/**
 * 解密小程序获取的用户手机号码
 * @param {*} openid 
 */
function decryptPhone(encryptData, iv, sessionKey, code) {
  // POST方式，参数放body
  return request.post(BASE_URL + '/decrypt/phone', { encryptData, iv,  sessionKey, code})
}

/**
 * 绑定公众号用户
 * @param {*} openid 小程序openid
 * @param {*} mpOpenid 公众号openid
 */
function bindMpUser(openid, mpOpenid) {
  // POST方式，参数放body
  return request.post(BASE_URL + '/bind/mp/user', { openid, mpOpenid })
}



module.exports = {
  getOpenid,
  loginByOpenid,
  decryptPhone,
  bindMpUser
} 